package com.fresh.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fresh.entity.FreshGoods;
import com.fresh.entity.Orders;
import com.fresh.system.dao.OrdersMapper;

import com.fresh.system.service.OrdersService;
import com.fresh.system.until.GoodsClient;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author Wx
 * @Date:2023/08/10/14:26
 * @Description:
 */
@GlobalTransactional(name = "fsp-create-order",rollbackFor = Exception.class)
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Resource
    private OrdersMapper ordersMapper;
    @Autowired
    private GoodsClient goodsClient;

    @Override
    public Orders add(Orders orders, Integer num, Integer goodsId) throws JsonProcessingException {
        FreshGoods goods = JSONObject.parseObject(new ObjectMapper().writeValueAsString(goodsClient.selectById(goodsId).getData()),FreshGoods.class);
        if (goods.getStock()-num <0) {
            throw new RuntimeException("商品数量不足");
        }
        goods.setStock(goods.getStock()-num);
        goodsClient.updateById(Math.toIntExact(goods.getId()),goods.getStock());
        ordersMapper.insert(orders);
        return orders;
    }
}
